package io.framework.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.framework.common.constant.Constant;
import io.framework.common.page.PageData;
import io.framework.common.service.impl.BaseServiceImpl;
import io.framework.common.utils.ConvertUtils;
import io.framework.modules.security.password.PasswordUtils;
import io.framework.modules.security.user.SecurityUser;
import io.framework.modules.security.user.UserDetail;
import io.framework.modules.sys.dao.SysUserDao;
import io.framework.modules.sys.dto.SysUserDTO;
import io.framework.modules.sys.entity.SysUserEntity;
import io.framework.modules.sys.enums.SuperAdminEnum;
import io.framework.modules.sys.service.SysDeptService;
import io.framework.modules.sys.service.SysRoleUserService;
import io.framework.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static io.framework.modules.air.utils.AirFileCommonUtil.readExcel;


/**
 * 系统用户
 * 
 *
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysRoleUserService sysRoleUserService;
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public PageData<SysUserDTO> page(Map<String, Object> params) {
		//转换成like
		paramsToLike(params, "username");

		//分页
		IPage<SysUserEntity> page = getPage(params, Constant.CREATE_DATE, false);

		//查询
		List<SysUserEntity> list = baseDao.getList(params);

		return getPageData(list, page.getTotal(), SysUserDTO.class);
	}

	@Override
	public List<SysUserDTO> list(Map<String, Object> params) {
		//普通管理员，只能查询所属部门及子部门的数据
		UserDetail user = SecurityUser.getUser();
		if(user.getSuperAdmin() == SuperAdminEnum.NO.value()) {
			params.put("deptIdList", sysDeptService.getSubDeptIdList(user.getDeptId()));
		}

		List<SysUserEntity> entityList = baseDao.getList(params);

		return ConvertUtils.sourceToTarget(entityList, SysUserDTO.class);
	}

	@Override
	public SysUserDTO get(Long id) {
		SysUserEntity entity = baseDao.getById(id);

		return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
	}

	@Override
	public SysUserDTO getByUsername(String username) {
		SysUserEntity entity = baseDao.getByUsername(username);
		return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
	}

	@Override
	public SysUserDTO getByRealName(String realName) {
		SysUserEntity entity = baseDao.getByRealName(realName);
		return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(SysUserDTO dto) {
		SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);

		//密码加密
		String password = PasswordUtils.encode(entity.getPassword());
		entity.setPassword(password);

		//保存用户
		entity.setSuperAdmin(SuperAdminEnum.NO.value());
		insert(entity);

		//保存角色用户关系
		sysRoleUserService.saveOrUpdate(entity.getId(), dto.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysUserDTO dto) {
		SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);

		//密码加密
		if(StringUtils.isBlank(dto.getPassword())){
			entity.setPassword(null);
		}else{
			String password = PasswordUtils.encode(entity.getPassword());
			entity.setPassword(password);
		}

		//更新用户
		updateById(entity);

		//更新角色用户关系
		sysRoleUserService.saveOrUpdate(entity.getId(), dto.getRoleIdList());
	}

	@Override
	public void delete(Long[] ids) {
		//删除用户
		baseDao.deleteBatchIds(Arrays.asList(ids));

		//删除角色用户关系
		sysRoleUserService.deleteByUserIds(ids);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updatePassword(Long id, String newPassword) {
		newPassword = PasswordUtils.encode(newPassword);

		baseDao.updatePassword(id, newPassword);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updatePasswordss(Long id, String newPassword) {
		//newPassword = PasswordUtils.encode(newPassword);

		baseDao.updatePasswordss(id, newPassword);
	}

	@Override
	public int getCountByDeptId(Long deptId) {
		return baseDao.getCountByDeptId(deptId);
	}



	/**
	 * @param url
	 * @return
	 */
	@Override
	public List<SysUserDTO> readuser(String url) {
		Workbook workbook = readExcel(url);
		if (workbook.getNumberOfSheets() <= 0) return null;
		List<SysUserDTO> airNumberDTOS = null;
		if (workbook != null) {
			airNumberDTOS = new ArrayList<>();
			Sheet sheet = workbook.getSheetAt(0);
			int rown = sheet.getPhysicalNumberOfRows();
			Row row = null;
			for (int i = 1; i < rown; i++) {
//				if (i < 5) {
//					continue;
//				}
				row = sheet.getRow(i);
				if (row != null) {
//					if (StringUtils.isNotBlank(getCellFormatValue(row.getCell(0)) + "") &&
//							StringUtils.isNotBlank(getCellFormatValue(row.getCell(1)) + "") &&
//							StringUtils.isNotBlank(getCellFormatValue(row.getCell(2)) + "")) {
						//赋值
						SysUserDTO airNumberDTO = setSysuser(1,row);
						if (airNumberDTO != null ) {
							airNumberDTO.setPassword("123456");
							airNumberDTO.setSuperAdmin(0);
							airNumberDTOS.add(airNumberDTO);
						}
	//				}
				}
			}
		}
		return airNumberDTOS;
	}

	@Override
	public SysUserDTO getByMobile(String mobile) {
		SysUserEntity entity = baseDao.getByMobile(mobile);
		return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
	}

	public static Object getCellFormatValue(Cell cell) {
		Object cellValue = null;
		if (cell != null) {
			// 如果是字符串，直接获取值
			CellType cellType = cell.getCellTypeEnum();
			if (cellType.equals(CellType.STRING)) {
				cellValue = cell.getStringCellValue().replaceAll(" ", "");
			} else if (cellType.equals(CellType.NUMERIC)) {
				if (DateUtil.isCellDateFormatted(cell)) {
					//转换为日期格式YYYY-mm-dd
					cellValue = cell.getDateCellValue();
				} else {
					//数字
					cellValue = cell.getNumericCellValue();
					if (cellValue instanceof Integer) {
						cellValue = new BigDecimal((Integer) cellValue);
					} else {
						cellValue = new BigDecimal(cellValue + "");
					}
				}
			}
			if ("NA".equals(cellValue)) {
				cellValue = new BigDecimal(0);
			}
		} else {
			cellValue = "";
		}
		return cellValue;
	}


	public static SysUserDTO setSysuser(Integer type, Row row) {
		SysUserDTO airDTO = new SysUserDTO();
		int i = 0;
		airDTO.setUsername((String) getCellFormatValue(row.getCell(i++)));
		airDTO.setRealName((String) getCellFormatValue(row.getCell(i++)));
		Object object0 =getCellFormatValue(row.getCell(i++));
		airDTO.setGender(Double.valueOf(String.valueOf(object0)).intValue());
		airDTO.setEmail((String) getCellFormatValue(row.getCell(i++)));
		BigDecimal bd = new BigDecimal(getCellFormatValue(row.getCell(i++)).toString());//要修改的值，需要string类型
		airDTO.setMobile(bd.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString());
		return airDTO;
	}


}
